package com.lg.partition12;

import java.io.*;
import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2022/4/12 10:39
 */
public class P1194买礼物 {

    private static final int N = 510;
    private static int[] parent = new int[N];
    private static Edge[] edges = new Edge[N * N];
    private static int n, m, tot = 0;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        m = Integer.parseInt(ss[0]);
        n = Integer.parseInt(ss[1]);
        for (int i = 1; i <= n; i++) {
            ss = reader.readLine().split(" ");
            for (int j = 1; j <= n; j++) {
                int c = Integer.parseInt(ss[j - 1]);
                if (c == 0) continue;
                edges[tot++] = new Edge(i, j, c);
            }
        }
        //超级源点连边
        for (int i = 1; i <= n; i++) edges[tot++] = new Edge(0, i, m);
        writer.write(kruskal() + "\n");
        writer.flush();
    }

    private static int kruskal() {
        for (int i = 1; i <= n; i++) parent[i] = i;
        Arrays.sort(edges, 0, tot);
        int ans = 0;
        for (int i = 0; i < tot; i++) {
            int u = edges[i].u, v = edges[i].v, w = edges[i].w;
            int p1 = find(u), p2 = find(v);
            if (p1 != p2) {
                parent[p1] = p2;
                ans += w;
            }
        }
        return ans;
    }

    private static int find(int x) {
        if (x != parent[x]) parent[x] = find(parent[x]);
        return parent[x];
    }

    private static class Edge implements Comparable<Edge> {
        private int u, v, w;

        public Edge(int u, int v, int w) {
            this.u = u;
            this.v = v;
            this.w = w;
        }

        @Override
        public int compareTo(Edge o) {
            return Integer.compare(w, o.w);
        }
    }
}
